package com.adou.shiro.filter;

import com.adou.common.util.UdpGetClientMacAddr;
import com.adou.common.util.userauth.interfaceUtils;
import com.adou.shiro.token.TokenManager;
import com.adou.shiro.util.ShiroFilterUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class PermissionFilter extends AccessControlFilter {

    private static final Logger logger = LoggerFactory.getLogger(PermissionFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        //先判断带参数的权限判断
        Subject subject = getSubject(servletRequest, servletResponse);
        if (null != o) {
            String[] arra = (String[]) o;
            for (String permission : arra) {
                if (subject.isPermitted(permission)) {
                    return Boolean.TRUE;
                }
            }
        }
        HttpServletRequest httpRequest = ((HttpServletRequest) servletRequest);

        String uri = httpRequest.getRequestURI();//获取URI
        if (null != uri) {
            String basePath = httpRequest.getContextPath();//获取basePath
            if (uri.startsWith(basePath)) {
                uri = uri.replace(basePath, "").replace("//", "/");
            }
        }
        if (subject.isPermitted(uri)) {
            return Boolean.TRUE;
        }
        Map<String, String> resultMap = new HashMap<>();
        Object permission = TokenManager.getVal2Session("permission");
        if (permission == null) {
            String id = String.valueOf(TokenManager.getIdByKey());
            String userid = TokenManager.getUserIdByKey();
            String sessionid = (String) TokenManager.getSessionIdByKey();
            String[] permarr = {uri};
            String ip = UdpGetClientMacAddr.getIP((HttpServletRequest) servletRequest);
            if (sessionid != null && id != null && userid != null) {
                //检查用户权限
                JSONObject json = interfaceUtils.checkUserPermission(TokenManager.getSysTypeByKey(), sessionid, userid,ip, permarr, "utf-8");
                if (json == null || json.isEmpty()) {
                    if (ShiroFilterUtils.isAjax(servletRequest)) {
                        logger.error("当前用户权限响应异常，并且是Ajax请求！");
                    }
                    resultMap.put("result", "600");
                    resultMap.put("msg", "当前用户权限响应异常");//当前用户没有登录或登陆异常！
                } else if (json.getIntValue("result") == 1) {
                    JSONArray inarr = json.getJSONArray("data");
                    if (inarr.getIntValue(0) == 1) {
                        return Boolean.TRUE;
                    } else {
                        if (ShiroFilterUtils.isAjax(servletRequest)) {
                            logger.error("当前用户无此权限，并且是Ajax请求！");
                        }
                        resultMap.put("result", "601");
                        resultMap.put("msg", "当前用户无此权限");//当前用户无权限！
                    }
                } else {
                    if (ShiroFilterUtils.isAjax(servletRequest)) {
                        logger.error(json.getString("msg") + "用户权限效验失败，并且是Ajax请求！");
                    }
                    resultMap.put("result", "602");
                    resultMap.put("msg", json.getString("msg"));
                }
            } else {
                if (ShiroFilterUtils.isAjax(servletRequest)) {
                    logger.error("当前用户尚未登陆，并且是Ajax请求！");
                }
                resultMap.put("result", "603");
                resultMap.put("msg", "当前用户尚未登陆");//当前用户参数异常！
            }
        } else {
            Set<String> list = (HashSet<String>) permission;
            if (list.contains(uri)) {
                return Boolean.TRUE;
            } else {
                if (ShiroFilterUtils.isAjax(servletRequest)) {
                    logger.error("当前用户无此权限，并且是Ajax请求！");
                }
                resultMap.put("result", "601");
                resultMap.put("msg", "当前用户无此权限");//当前用户无权限！
            }
        }
        ShiroFilterUtils.out(servletResponse, resultMap);
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        subject.logout();
        return Boolean.FALSE;
    }

}
